#
# Package.
#

package iSOCK::Controller::Report::Components;

#
# Dependencies.
#

use Sort::Naturally qw( nsort );
use Try::Tiny;

#
# Parent.
#

use Moose;
use namespace::autoclean;

BEGIN { extends 'iSOCK::Controller::Root' }

__PACKAGE__->meta->make_immutable;

no Moose;

#
# Documentation.
#

=head1 NAME

iSOCK::Controller::Report::Components - Report Controller for iSOCK

=head1 DESCRIPTION

[enter your description here]

=head1 METHODS

=cut

#
# Subs.
#

sub index :Path :Args(0) {
  my ( $self, $c ) = @_;
  
  my $cookie    = 'isock-report-components';
  my $parameter = $c->request->parameters;
  
  my $checked;
  
  if ( $c->request->method eq 'POST' && $parameter->{form_report_components} ) {
    $checked->{$_} = 1 for nsort grep { ! m/form_report_components/ && ! m/scope/ } keys %$parameter;
    
    if ( $checked ) {
      $c->response->cookies->{$cookie} = { value => join ( ',', nsort keys %$checked ), expires => '+3M' };
    }
    
    try {
      my $app_m = $c->model ( 'App' );
      
      my $components = $app_m->components_report ({
        c        => $c,
        scope    => $parameter->{scope},
        products => [ nsort grep {   m/-[A-Z]$/ } keys %$checked ],
        types    => [  sort grep { ! m/-[A-Z]$/ } keys %$checked ],
      });
      
      $c->stash ( components => $components );
      
      if ( my $session_path = $self->session_path ( $c ) ) {
        if ( my $user_r = $app_m->user_r ( $c ) ) {
          my $file = 'components-report.xls';
          
          $app_m->components_report_to_xls_file ({ report => $components, file => "$session_path/$file", author => $user_r->name });
          
          $c->stash ( xls_file => "/tmp/" . $c->sessionid . "/$file" );
        }
      }
    }
    catch {
      ( my $why = $_ ) =~ s/ at \/.+\.$//;
      
      $c->stash ( action_failed => $why );
    };
  }
  elsif ( my $cookie_id = $c->request->cookies->{$cookie}) {
    $checked->{$_} = 1 for split ',', $cookie_id->value;
  }
  
  $c->stash (
    products          => $c->model ( 'App' )->products_loh ( $c ),
    checked           => $checked,
    component_type_rs => $c->model ( 'App::ComponentType' ),
  );

  $c->forward ( qw( iSOCK::Controller::Root render_view ) );
}

#
# Documentation.
#

=head1 AUTHOR

Xavier Caron

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

#
# End of iSOCK::Controller::Report::Components.
#

1;
